package com.example.demo.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;

public class AesUtil {

    /**
     * 加密
     */
    public static String encrypt(String text, String password) throws Exception {

        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = text.getBytes("utf-8");
        cipher.init(1, genKey(password));
        byte[] result = cipher.doFinal(byteContent);
        return parseByte2HexStr(result);

    }

    /**
     * 解密
     */
    public static String decrypt(String encryptText, String password) throws Exception {

        byte[] decryptFrom = parseHexStr2Byte(encryptText);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(2, genKey(password));
        byte[] result = cipher.doFinal(decryptFrom);
        return new String(result);

    }

    private static SecretKeySpec genKey(String password) throws NoSuchAlgorithmException {
        byte[] enCodeFormat = { 0 };
        KeyGenerator kgen = javax.crypto.KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(password.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        enCodeFormat = secretKey.getEncoded();
        return new SecretKeySpec(enCodeFormat, "AES");
    }

    private static String parseByte2HexStr(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);

            result[i] = ((byte) (high * 16 + low));
        }
        return result;
    }

//    public static void main(String[] args) throws Exception {
//        String content = "{\n" + "\"id\": 1,\n" + "\"name\": \"张三\",\n" + "\"address\":\"上海市浦东新区\"\n" + "}";
//
//        System.out.println(AesUtil.encrypt(content, "123456"));
//
//    }

}
